<h1>{{#if category.id}}编辑分类{{else}}添加分类{{/if}}</h1>

<form action="/admin/categories{{#if category.id}}/{{category.id}}{{/if}}" method="post">
    {{#if category.id}} <input type="hidden" name="_method" value="put" />{{/if}}
    <div class="mb-3">
        <label for="name" class="form-label">名称</label>
        <input type="text" class="form-control" id="name" name="name" value="{{category.name}}">
    </div>
    <div class="mb-3">
        <label for="parent" class="form-label">父权限</label>
        <div id="parentTree" class="border rounded p-3"></div>
    </div>
    <div class="mb-3">
        <label for="status" class="form-label">状态</label>
        <select class="form-control" name="status" id="status">
            <option value="1" {{#if category.status}}selected{{/if}}>激活</option>
            <option value="0" {{#unless category.status}}selected{{/unless}}>未激活</option>
        </select>
    </div>
    <button type="submit" class="btn btn-primary">保存</button>
</form>

<script>
    const categoryTree = {{{json categoryTree}}}

    function renderTree(categories){
        let html = `<ul class="list-unstyled">`
        const selectedParentId = {{{def category}}}
        categories.forEach(function (category) {
            html+= `
                <li class="mb-2">
                    <div class="d-flex align-items-center">
                    ${category.children?.length>0?`<span class="toggle me-2 cursor-pointer"><i class="bi bi-folder-minus"></i></span>`:'<span class="me-4"></span>'}
                        <label class="form-check-label">
                            <input type="radio" class="form-check-input" ${category.id == selectedParentId?'checked' :''} name="parentId" value="${category.id}" />
                            ${category.name}
                        </label>
                    </div>
                        ${category.children?.length>0?`<div class="children ms-4">${renderTree(category.children)}</div>`: ''}
                    
                </li>
            `
        })
        html += '</ul>'
        return html
    }
    $(function () {
        $('#parentTree').html(renderTree(categoryTree))
        function hideChildren($tr, id){
            const $children = $tr.nextAll(`tr[data-parent="${id}"]`)
            $children.each(function(){
                const childId = $(this.data('id'))
                hideChildren($(this), childId)
            })
            $children.hide()
        }
        $('body').on('click', '.togger', function () {
            const children = $(this).parent().siblings('.children')
            if (children.is('.visible')) {
                children.hide()
                $(this).html('<i class="bi bi-folder-plus"></i>')
            } else {
                children.show()
                $(this).html('<i class="bi bi-folder-minus"></i>')
            }
        })
    })
</script>